class Solution(object):
    def surfaceArea(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        m = len(grid)
        n = len(grid[0])
        t = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j]:
                    t += 2 + 4 * grid[i][j]
                if i > 0:
                    t -= 2 * min(grid[i][j], grid[i - 1][j])
                if j > 0:
                    t -= 2 * min(grid[i][j - 1], grid[i][j])
        return t
